from . import user_blue
from info.utils.common import check_islogin
from flask import render_template, g, redirect, request,jsonify,current_app
from info.utils.response_code import *
from info import db,models
from info.utils.image_storage import storage
from info import constants



# 显示个人中心
@user_blue.route("/info")
@check_islogin
def user_login_data():
    user = g.user
    if not user:
        return redirect("/")
    data = {
        "user_info": user.to_dict() if user else None
    }
    return render_template("news/user.html", data=data)


# 修改昵称
@user_blue.route("/base_info", methods=["POST", "GET"])
@check_islogin
def base_info():
    user = g.user
    # 判断请求方式，第一次请求返回到修改页面
    if request.method == "GET":
        data ={
            "user_info": user.to_dict if user else None
        }
        return render_template("news/user_base_info.html", data=data)
    # 判断是否登录
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map.get(RET.SESSIONERR))
    #  获取浏览器发送的参数
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")
    # 判断是参数是否收到
    if not all([nick_name, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))

    #　修改数据
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    # 提交数据库
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="修改成功!")

# 修改头像
@user_blue.route("/pic_info", methods=["POST","GET"])
@check_islogin
def pic_info():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map.get(RET.SESSIONERR))

    if request.method == "GET":
        data = {
            "user_info":user.to_dict() if user else None
        }

        print()
        return render_template("news/user_pic_info.html", data=data)
    # 拿到上传图片
    avatar_url = request.files.get("avatar").read()
    key = storage(avatar_url)
    user.avatar_url = key
    db.session.commit()
    data ={
        "user_info": user.to_dict() if user else None,
        "avatar_url": constants.QINIU_DOMIN_PREFIX + key
    }
    return jsonify(errno=RET.OK, errmsg="修改头像成功!", data=data)


# 修改密码
@user_blue.route("/pass_info", methods=["POST", "GET"])
@check_islogin
def pass_info():
    user = g.user
    # 第一次请求ＧＥＴ请求返回到修改密码页面
    if request.method == "GET":
        data = {
            "user_info": user.to_dict if user else None
        }
        return render_template("news/user_pass_info.html", data=data)
    #  获取浏览器数据
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))

    #　获取当前用户的密码是的跟old_password一致
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg=error_map.get(RET.PWDERR))
    # 修改密码
    user.password = new_password
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="密码修改失败！")

    return jsonify(errno=RET.OK, errmsg="密码修改成功！")

# 用户收藏
@user_blue.route("/collection")
@check_islogin
def user_collection():
    user = g.user
    page = request.args.get("p")
    try:
        page = int(page)
    except Exception as e:
        page = 1

    # 查出所有的收藏新闻分页　每页１０条
    paginate = user.collection_news.paginate(page,10,False)
    # 总页数
    total_page = paginate.pages
    # 当前页
    cur_page = paginate.page
    # 每页的新闻对象
    items = paginate.items
    collection_news_list = [item.to_dict() for item in items]
    data ={
        "total_page": total_page,
        "current_page": cur_page,
        "collections": collection_news_list
    }
    return render_template("news/user_collection.html", data=data)

# 新闻发布
@user_blue.route("/news_release",methods=["GET", "POST"])
@check_islogin
def news_release():
    user = g.user

    # 第一次请求加载分类信息
    if request.method == "GET":
        categorys = models.Category.query.all()
        category_list = [category.to_dict() for category in categorys if category.to_dict().get("id") != 1]
        data = {
            "categories": category_list,
        }
        return render_template("news/user_news_release.html", data=data)

    # 获取浏览器数据
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")
    source = "个人发布"

    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    # 上传到七牛云
    index_image = index_image.read()
    key = storage(index_image)

    news = models.News()
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.index_image_url = key
    news.content = content
    news.source = source
    news.user_id = user.id
    # 需要增加一个状态
    news.status = 1
    # 提交
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库存储失败!")
    return jsonify(errno=RET.OK, errmsg="添加成功!")

#　新闻发布列表
@user_blue.route("/news_list")
@check_islogin
def news_list():
    user = g.user
    page = request.args.get("p","1")
    try:
        page = int(page)
    except Exception as e:
        page = 1
    # 分页
    paginate = models.News.query.filter(models.News.user_id == user.id).paginate(page, 5, False)
    # 总页数
    total_page = paginate.pages
    # 当前页
    cur_page = paginate.page
    # 信息
    items = paginate.items
    news_list = [item.to_review_dict for item in items]
    data  = {
        "current_page": cur_page,
        "total_page": total_page,
        "news_list": news_list
    }
    return render_template("news/user_news_list.html", data=data)



